package com.gcloud.controller.slb.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.gcloud.common.util.StringUtils;
import com.gcloud.controller.ResourceProviders;
import com.gcloud.controller.slb.dao.LoadBalancerDao;
import com.gcloud.controller.slb.entity.LoadBalancer;
import com.gcloud.controller.slb.model.DescribeLoadBalancerAttributeResponse;
import com.gcloud.controller.slb.model.DescribeLoadBalancersParams;
import com.gcloud.controller.slb.provider.ILoadBalancerProvider;
import com.gcloud.controller.slb.service.ILoadBalancerService;
import com.gcloud.core.exception.GCloudException;
import com.gcloud.framework.db.PageResult;
import com.gcloud.header.api.model.CurrentUser;
import com.gcloud.header.enums.ResourceType;
import com.gcloud.header.slb.model.LoadBalancerModel;
import com.gcloud.header.slb.msg.api.CreateLoadBalancerMsg;
import com.gcloud.header.slb.msg.api.CreateLoadBalancerReplyMsg;
import com.gcloud.header.slb.msg.api.ListenerPortAndProtocol;
import com.google.common.base.Strings;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Transactional(propagation = Propagation.REQUIRES_NEW)
@Service
public class LoadBalancerServiceImpl implements ILoadBalancerService {

    @Autowired
    private LoadBalancerDao lberDao;

    @Override
    public CreateLoadBalancerReplyMsg createLb(CreateLoadBalancerMsg msg) {
        return this.getProviderOrDefault().createLb(msg.getLoadBalancerName(), msg.getvSwitchId(), msg.getRegion(), msg.getCurrentUser());
    }

    @Override
    public void setLoadBalancerName(String loadBalancerId, String loadBalancerName) {
        LoadBalancer lber = lberDao.getById(loadBalancerId);
        if (null == lber) {
			log.debug("找不到负载均衡器");
            throw new GCloudException("0110101::找不到负载均衡器");
        }  
        lber.setName(loadBalancerName);
        List<String> updateField = new ArrayList<String>();
        updateField.add(lber.updateName(loadBalancerName));
        updateField.add(lber.updateUpdatedAt(new Date()));
        lberDao.update(lber, updateField);
        this.checkAndGetProvider(lber.getProvider()).updateBalancerName(lber.getProviderRefId(), loadBalancerName);

    }

    @Override
    public void deleteLoadBalancer(String loadBalancerId) {
        LoadBalancer lber = lberDao.getById(loadBalancerId);
        if (null == lber) {
            log.debug("找不到负载均衡");
            throw new GCloudException("0110302::找不到负载均衡");
        }
        lberDao.delete(lber);
        this.checkAndGetProvider(lber.getProvider()).deleteLoadBalancer(lber.getProviderRefId());  
    }

    private ILoadBalancerProvider getProviderOrDefault() {
        ILoadBalancerProvider provider = ResourceProviders.getDefault(ResourceType.SLB);
        return provider;
    }

    private ILoadBalancerProvider checkAndGetProvider(Integer providerType) {
        ILoadBalancerProvider provider = ResourceProviders.checkAndGet(ResourceType.SLB, providerType);
        return provider;
    }

	@Override
	public DescribeLoadBalancerAttributeResponse describeLoadBalancerAttribute(String loadBalancerId) {
		// TODO Auto-generated method stub
		LoadBalancer lber = lberDao.getById(loadBalancerId);
		if (null == lber) {
			log.debug("找不到负载均衡器");
            throw new GCloudException("0110402::找不到负载均衡器");
        }
		DescribeLoadBalancerAttributeResponse response = new DescribeLoadBalancerAttributeResponse();
		List<String> loadBalancerIds = new ArrayList<String>();
		loadBalancerIds.add(loadBalancerId);
		List<LoadBalancerModel> loadBalancers = lberDao.list(loadBalancerIds);
		for(LoadBalancerModel model: loadBalancers) {
			response.setLoadBalancerId(model.getLoadBalancerId());
			response.setLoadBalancerName(model.getLoadBalancerName());
			response.setLoadBalancerStatus(model.getLoadBalancerStatus());
			response.setVpcId(model.getVpcId());
			response.setvSwitchId(model.getvSwitchId());
			response.setAddress(model.getAddress());
			response.setCreateTime(model.getCreateTime());
			List<Integer> listenerPorts = new ArrayList<Integer>();
			List<ListenerPortAndProtocol> listenerPortsAndProtocol = new ArrayList<ListenerPortAndProtocol>();
			if( StringUtils.isNotBlank(model.getListener())) {
	            for(String listener: model.getListener().split(",")) {
	            	int index = listener.indexOf("#");
	            	int lastIndex = listener.lastIndexOf("#");
	            	
	            	String id = listener.substring(0, index);
	            	Integer port = Integer.valueOf(listener.substring(index+1, lastIndex));
	            	String protocol = listener.substring(lastIndex+1);
	            	listenerPorts.add(port);
	            	ListenerPortAndProtocol pp = new ListenerPortAndProtocol();
	            	pp.setListenerId(id);
	            	pp.setListenerPort(port);
	            	pp.setListenerProtocol(protocol);
	            	listenerPortsAndProtocol.add(pp);
	            }	
	            response.setListenerPorts(listenerPorts);
	            response.setListenerPortsAndProtocol(listenerPortsAndProtocol);
			}
		}
		
		return response;
	}

	@Override
	public PageResult<LoadBalancerModel> describeLoadBalancers(DescribeLoadBalancersParams params, CurrentUser currentUser) {
		// TODO Auto-generated method stub
		return lberDao.getByPage(params.getPageNumber(), params.getPageSize(), null, currentUser);
	}



}
